<?php

namespace App\Admin\Forms\Config;

use App\Models\Config as Model;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class CreateConfig extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $res = false;
        if ($input){
            $fields = ['module','group','name','title','value','type','content','required','rule'];
            try {
                $config = new Model;
                foreach ($input as $key=>$value){
                    if (in_array($key,$fields)){
                        $config[$key] = is_array($value)?json_encode($value,JSON_UNESCAPED_UNICODE):$value;
                    }
                }
                $res = $config->save();
            }catch (ModelNotFoundException|Exception $e){
                return $this->response()->error($e->getMessage())->refresh();
            }
        }
        return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->column(5, function () {
            $this->hidden('module');
            $this->select('group')->required()->options(\App\Models\Config::getGroupList());
            $this->text('name')->required();
            $this->text('title')->required();
            $this->textarea('value');
        });
        $this->column(7, function () {
            $this->select('type')->when(['radio','checkbox','select','multipleSelect'], function () {
                $this->keyValue('content');
            })->when('list', function () {
                $this->list('content');
            })->when(['text'], function () {
                $this->textarea('content');
            })->required()->options(\App\Models\Config::getTypeList());
//            ->when('embeds', function () {
//                $this->embeds('content');
//            })->when('list', function () {
//                $this->list('content');
//            })
//            $this->text('content');
//                    $form->text('extend');
//                    $form->text('setting');
//            'keyValue'      => '键值组',
//            'embeds'        => '固定键值对象',
//            'list'          => '一维数组',
//            'table'         => '二维数组（table）',
//            'array'         => '二维数组（array）',
            $states = [
                'on'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
            ];
            $this->switch('required');
            $this->textarea('rule');
        });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'module'  => 'admin',
            'required'=>0,
            'content'=>'',
            'rule'=>''
        ];
    }
}
